import { EVENT_CENTER_MANAGER_EVENTS } from '@app-cad/common/Constants';
import { userEvents } from '@app-cad/module';
import { BaseEventCenter } from './BaseEventCenter';

/**
 * 事件中心管理
 * @author: yinjianfeng
 * @date: 2024-08-24
 * @version: 1.0.0
 */
export class EventCenterManager {
  private _activeEventCenter: BaseEventCenter;
  private eventCenterMap: Map<string, BaseEventCenter> = new Map();

  addEventCenter(eventCenter: BaseEventCenter): EventCenterManager {
    if (!this.eventCenterMap.has(eventCenter.id)) {
      this.eventCenterMap.set(eventCenter.id, eventCenter);
    }
    return this;
  }

  switchTo(id: string) {
    const previousEventCenter = this._activeEventCenter;
    const nextEventCenter = this.eventCenterMap.get(id);

    if (nextEventCenter && nextEventCenter !== previousEventCenter) {
      if (previousEventCenter) {
        userEvents.emit(EVENT_CENTER_MANAGER_EVENTS.EVENT_CENTER_CHANGING);
        this._activeEventCenter.sleep();
      }

      this._activeEventCenter = nextEventCenter;
      this._activeEventCenter.init();

      if (previousEventCenter) {
        userEvents.emit(EVENT_CENTER_MANAGER_EVENTS.EVENT_CENTER_CHANGED, id);
      }
    }
  }

  getEventCenter(id: string) {
    if (this.eventCenterMap.has(id)) {
      return this.eventCenterMap.get(id);
    }
    return null;
  }

  get activeEventCenter() {
    return this._activeEventCenter;
  }

  get activeEventCenterId() {
    return this._activeEventCenter?.id;
  }

  get isSketchMode() {
    return this._activeEventCenter?.id === 'sketch';
  }
}

export const eventCenterManager = new EventCenterManager();
